<template>
  <div class="AddOnlineWork">
    <div class="AddOnlineWorkBox">
      <div class="header">
        <el-form :model="form">
          <el-form-item label="作业名称：">
            <el-input
              v-model="form.workName"
              autocomplete="off"
              placeholder="请输入作业名称"
              style="width: 280px"
            ></el-input>
          </el-form-item>
          <el-form-item label="截止时间：">
            <div class="block">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                style="width: 280px"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="学院名称：">
            <el-cascader
              style="width: 300px"
              :options="treeData"
              v-model="form.colleage"
              placeholder="请选择学院名称"
              clearable
              :props="{value: 'id' , checkStrictly: true }"
              @change="handleChange"
   
              :show-all-levels="false"
            ></el-cascader>
            <!-- <el-select v-model="form.colleage" placeholder="请选择专业">
              <el-option
                v-for="(item, index) in treeData"
                :key="index"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-form>
        <div class="btn">
          <el-button type="primary" @click="addWorkTitle">添加标题</el-button>
        </div>
      </div>

      <div class="mian">
        <div class="title">
          <span>在线测试</span>
        </div>
        <!-- 标题 -->
        <div class="content">
          <div
            class="content_box"
            v-for="(item, index) in onlineTestingList"
            :key="index"
          >
            <div class="content_box_title">
              <div class="content_box_title_left">
                <span>标题{{ index + 1 }}：</span>
                <el-input
                  v-model="item.titleName"
                  @blur="setTitleName(item)"
                  placeholder="请输入标题"
                  style="width: 200px"
                  class="input"
                ></el-input>
                <el-button type="primary" @click="addWorkTopic(item)">
                  添加题目
                </el-button>
              </div>

              <i
                v-if="onlineTestingList.length > 1"
                class="icon iconfont icon-shanchu"
                @click="delWorkTitle(item)"
              ></i>
            </div>

            <!-- 题目 -->
            <div
              class="content_box_topic"
              v-for="(it, ind) in item.topic"
              :key="ind"
            >
              <div class="content_box_topic_header">
                <span>题目{{ ind + 1 }}：</span>
                <p class="header_title" v-html="it.questionsStems"></p>
                <i
                  class="icon iconfont icon-shanchu"
                  @click="delWorkTopic(item, it)"
                ></i>
              </div>

              <div class="answerFixedBox">
                <div
                  class="answerFixed"
                  v-for="(ite, i) in it.answerFixed"
                  :key="i"
                >
                  <div>
                    <span v-html="ite.content"></span>
                    <span class="dian">.</span>
                    <span v-html="ite.optionsName"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 确定 / 取消按钮 -->
        <div class="mian_btn">
          <el-button @click="closeAddOrEdit">取 消</el-button>
          <el-button type="primary" @click="submitWork">确 定</el-button>
        </div>
      </div>
      <el-dialog
        title="选择试题"
        :visible.sync="dialogVisible"
        min-width="30%"
        :before-close="handleClose"
      >
        <!-- 表格 -->
        <div class="bottomMian">
          <el-table
            ref="multipleTable"
            :data="questionsList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50"> </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column prop="typeName" label="学科"></el-table-column>
            <el-table-column prop="questionsTypeClone" label="题型">
            </el-table-column>
            <el-table-column prop="questionsStems" label="题干">
              <template slot-scope="scope">
                <div class="upLoadImgAndT">
                  <div
                    class="uploadImg"
                    v-html="scope.row.questionsStems"
                  ></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="grades" label="分数"> </el-table-column>
            <el-table-column prop="difficulty" label="难度"> </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="10"
              prev-text="上一页"
              next-text="下一页"
              layout=" prev, pager, next"
              :total="total"
            >
            </el-pagination>
            <div class="jumper">
              跳到第
              <input type="text" ref="currentPage" value="1" />
              页
            </div>
            <button class="submit" @click="goPage">确定</button>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getDetailApi,
  addOnlineWorkApi,
  editOnlineWorkApi,
  getQuestionsListApi,
} from "@/api/onlineWork/onlineWork";
import { colleageTreeDataApi } from "@/api/basics/college.js";
import moment from "moment";
export default {
  data() {
    return {
      detailObj: {}, // 详情数据
      form: {
        id: "",
        date: "",
        workName: "",
        colleage:'',
      },
      onlineTestingList: [
        {
          titleName: "",
          topic: [],
        },
      ],
      treeData:[],
      dialogVisible: false,
      topicId: "",
      currentPage: 1,
      pageSize: 10,
      questionsList: [],
      total: 0,
      multipleSelection: [],
      edit: false,
    };
  },

  created() {
    this.getQuestionsList({
      pageNum: this.currentPage,
      pageSize: this.pageSize,
    });
  },

  mounted() {
    let { id } = this.$route.query;
    this.edit = id ? true : false;
    if (id) {
      // 根据id 查询详情数据
      getDetailApi({ id }).then((res) => {
        this.detailObj = res.data;
        this.form = {
          date: res.data.deadline,
          workName: res.data.taskName,
          id,
        };
        this.onlineTestingList = res.data.title.map((item, index) => {
          return { ...item, id: index };
        });
      });
    }
    this.getTree()
  },

  methods: {
    // 获取题库列表
    getQuestionsList(data) {
      getQuestionsListApi(data).then((res) => {
        res.rows.forEach((item) => {
          if (item.questionsType == "0") {
            item.questionsTypeClone = "单选题";
          } else if (item.questionsType == "1") {
            item.questionsTypeClone = "多选题";
          } else if (item.questionsType == "2") {
            item.questionsTypeClone = "判断题";
          } else if (item.questionsType == "3") {
            item.questionsTypeClone = "填空题";
          } else if (item.questionsType == "4") {
            item.questionsTypeClone = "简答题";
          }
        });
        this.questionsList = res.rows;
        this.total = res.total;
      });
    },

    // 添加标题
    addWorkTitle() {
      this.onlineTestingList.push({
        titleName: "",
        topic: [],
        id: this.onlineTestingList.length,
      });
    },

    // 删除标题
    delWorkTitle(data) {
      this.$confirm("删除标题，此标题下所有题目也将删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.onlineTestingList.forEach((item, index) => {
            if (item.id == data.id) {
              this.onlineTestingList.splice(index, 1);
            }
          });
        })
        .catch(() => {});
    },

    // 修改标题名称
    setTitleName(data) {
      this.onlineTestingList.forEach((item) => {
        if (item.id == data.id) {
          item.topic.forEach((it) => {
            it.titleName = data.titleName;
          });
        }
      });
    },

    // 添加题目
    addWorkTopic(data) {
      this.dialogVisible = true;
      this.topicId = data.id;
    },

    // 取消选择试题
    handleClose() {
      this.dialogVisible = false;
    },

    // 确定选择试题
    handleSubmit() {
      this.onlineTestingList.forEach((item) => {
        if (item.id == this.topicId) {
          this.multipleSelection.forEach((it) => {
            item.topic.push({
              questions: "",
              questionsStems: it.questionsStems,
              titleId: it.questionsId,
              titleName: item.titleName,
              answerFixed: it.options ? JSON.parse(it.options) : [],
            });
          });
        }
      });
      this.dialogVisible = false;
    },

    // 删除题目
    delWorkTopic(val, data) {
      this.$confirm("确定要删除此题目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.onlineTestingList.forEach((item) => {
            if (item.id == val.id) {
              item.topic.forEach((it, ind) => {
                if (it.titleId == data.titleId) {
                  item.topic.splice(ind, 1);
                }
              });
            }
          });
        })
        .catch(() => {});
    },

    // 取消
    closeAddOrEdit() {
      this.$router.go(-1);
    },
    handleChange(value) {
      console.log(value);
    },
    //获取学院
     getTree() {
      colleageTreeDataApi()
        .then((res) => {
          this.treeData = res.data;
          console.log('4556',this.treeData)
        })
        .catch(() => {});
    },
    // 确定
    submitWork() {
      let data = {
        id: this.form.id,
        taskName: this.form.workName,
        deadline: moment(this.form.date).format("YYYY-MM-DD"),
        title: this.onlineTestingList,
        colleage: this.form.colleage.toString(),
        major: this.detailObj.major,
        clbum: this.detailObj.clbum,
        createBy: this.detailObj.createBy,
      };
      if (this.edit) {
        this.$message("修改中");
        editOnlineWorkApi(data).then((res) => {
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.$router.push("/onlineWork");
          } else {
            this.$message.error("修改失败");
          }
        });
      } else {
        addOnlineWorkApi(data).then((res) => {
          if (res.code === 200) {
            this.$message.success("添加成功");
            this.$router.push("/onlineWork");
          } else {
            this.$message.error("添加失败");
          }
        });
      }
    },

    // 选择 / 全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 更改当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getQuestionsList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },

    // 跳转当前页
    goPage() {
      let { value } = this.$refs.currentPage;
      this.currentPage = Number(value);
      this.getQuestionsList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.AddOnlineWork {
  width: 100%;
  height: 100%;
  padding: 0 15px 15px;
  box-sizing: border-box;

  .AddOnlineWorkBox {
    width: 100%;
    height: 100%;
    background-color: #fff;
    box-sizing: border-box;
    border-radius: 10px;
    padding: 40px 22px;

    .mian {
      margin-top: 30px;
      display: flex;
      flex-direction: column;

      .title {
        height: 60px;
        background-color: #f2f3f7;
        padding-left: 26px;
        display: flex;
        align-items: center;
      }

      .content {
        flex: 1;
        box-sizing: border-box;

        .content_box {
          border: #d4d4d4 solid 1px;
          border-top: none;

          .content_box_title {
            padding: 40px 40px 40px 26px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: solid 1px #d4d4d4;
            .el-input {
              margin: 0 10px;
            }
          }

          .content_box_topic {
            padding: 30px 0 30px 0;
            margin: 0 40px 0 26px;
            border-bottom: solid 1px #d4d4d4;

            .content_box_topic_header {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .header_title {
                flex: 1;
              }
            }
            .questionsStems {
              padding-top: 10px;
            }
            .answerFixedBox {
              display: flex;
              padding-top: 15px;
              .answerFixed {
                flex: 1;
                display: flex;
                div {
                  display: flex;
                  align-items: center;
                  .dian {
                    padding: 0 5px 0 0;
                    font-weight: bold;
                  }
                }
              }
            }
          }

          .content_box_topic:nth-last-child(1) {
            border: none;
          }
        }
        .content_box:nth-child(1) {
          border-top: #d4d4d4 solid 1px;
        }
      }

      .mian_btn {
        margin-top: 50px;
        display: flex;
        align-items: center;
        justify-content: center;

        .el-button {
          width: 100px;
        }
      }
    }

    ::v-deep .el-dialog__wrapper {
      border-radius: 10px;
      .el-dialog {
        border-radius: 10px;
        margin-top: 5vh !important;
        .el-dialog__header {
          border-radius: 8px 8px 0 0;
        }

        .el-dialog__footer {
          text-align: center;
        }
      }
    }

    .bottomMian {
      box-sizing: border-box;

      .icon {
        cursor: pointer;
        font-size: 20px;
        font-weight: bold;
        margin: 0 6px;
      }

      .checkStudent {
        margin: 0 0 0 6px;
      }
    }

    .pagination {
      display: flex;
      align-items: center;
      justify-content: right;
      margin-top: 20px;
      margin-right: 20px;
      padding: 0 0 20px 0;

      .jumper {
        font-size: 14px;
        margin-left: 20px;
        margin-right: 10px;
        display: flex;
        align-items: center;

        input {
          width: 40px;
          height: 26px;
          margin: 0 5px;
          text-align: center;
          border: solid 1px #e6e6e6;
          border-radius: 5px;
          color: #666;
          outline-style: none;
        }
      }

      button {
        height: 28px;
        line-height: 28px;
        border-radius: 5px;
        font-size: 14px;
        padding: 0 8px;
        border: solid 1px #e6e6e6;
        color: #666;
      }

      .submit {
        color: #fff;
        background-color: #4895db;
        border: solid 1px #4895db;
      }
    }
  }
}
</style>